package dbs

import (
	"database/sql"
	"fmt"
	"log"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

// 数据库配置
type Config struct {
	UserName string
	PassWord string
	Host     string
	PORT     string
	DATABASE string
}

var MysqlDbMap map[string]*sql.DB

// 初始化数据库链接
func init() {
	MysqlDbMap = make(map[string]*sql.DB)
	DbConfig := Config{
		UserName: "root",
		PassWord: "123456",
		Host:     "127.0.0.1",
		PORT:     "3306",
		DATABASE: "ndcube",
	}

	Db := conn(DbConfig)
	MysqlDbMap["default"] = Db

	monitorDbConfig := Config{
		UserName: "root",
		PassWord: "rfvTGB45!",
		Host:     "81.68.153.138",
		PORT:     "3306",
		DATABASE: "devmonitor2",
	}

	monitorDb := conn(monitorDbConfig)
	MysqlDbMap["monitor"] = monitorDb
}

func conn(c Config) *sql.DB {
	var MysqlDb *sql.DB
	var MysqlDbErr error

	dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", c.UserName, c.PassWord, c.Host, c.PORT, c.DATABASE)

	// 打开连接失败
	MysqlDb, MysqlDbErr = sql.Open("mysql", dbDSN)
	//defer MysqlDb.Close();
	if MysqlDbErr != nil {
		log.Println("dbDSN: " + dbDSN)
		panic("数据源配置不正确: " + MysqlDbErr.Error())
	}

	// 最大连接数
	MysqlDb.SetMaxOpenConns(100)
	// 闲置连接数
	MysqlDb.SetMaxIdleConns(20)
	// 最大连接周期
	MysqlDb.SetConnMaxLifetime(100 * time.Second)

	if MysqlDbErr = MysqlDb.Ping(); nil != MysqlDbErr {
		panic("数据库链接失败: " + MysqlDbErr.Error())
	}

	return MysqlDb
}
